Ti.include('../viewHelper/noticiesViews.js');
var win = Ti.UI.currentWindow;
var views = noticiesViews.getViews();

win.add(views.nav);
views.activityIndicatorView.add(views.activityIndicator);
views.nav.window.add(views.activityIndicatorView);
views.nav.window.setLeftNavButton(views.refreshButton);
views.nav.window.add(views.tableview);

var xhr = Ti.Network.createHTTPClient({
	timeout : Ti.App.config.connection_timeout,
	validatesSecureCertificate : false
});

var data = [];
var newsLoaded = Ti.App.Properties.getBool("newsLoaded",false);
Ti.App.Properties.setBool("newsLoaded",newsLoaded);

//carreguem els mesos aqui per no haver de carregarlos cada vegada que generem una data
var monthNames= [L("Month0"),L("Month1"),L("Month2"),L("Month3"),L("Month4"),L("Month5"),L("Month6"),L("Month7"),L("Month8"),L("Month9"),L("Month10"),L("Month11")];

views.tableview.search.addEventListener('focus', function(){
	views.tableview.backgroundColor='#000';
});

views.tableview.search.addEventListener('blur', function(){
	views.tableview.backgroundColor='transparent';
});

function getNow(){
	return Math.round(new Date().getTime() / 1000);
}

views.tableview.addEventListener('click',function(e){
	var detailViews = noticiesViews.getNoticiaDetailWindow(e.row.titol,e.row.tipus);
	
	if (detailViews.wb.tipusPagina == 0){
		detailViews.wb.addEventListener('load',function(e){
			detailViews.wb.evalJS("var nav = document.getElementById('nav');if (nav != null){nav.parentNode.removeChild(nav);}var sidebar = document.getElementById('sidebar');if (sidebar != null){sidebar.parentNode.removeChild(sidebar);}document.getElementById('maincontent').style.width='auto';document.getElementsByTagName('body')[0].style.fontSize='18px';");
			Ti.App.fireEvent('fontchange', {amount:+5});
			detailViews.wb.repaint();
		});
	}
	
	if (detailViews.wb.tipusPagina==1){
		detailViews.wb.html='<html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=320"/></head><body style="background:#000;margin-top:0px;margin-left:0px"><div><object width="320" height="150"><param name="movie" value="'+e.row.link+'"></param><param name="wmode" value="transparent"></param><embed src="'+e.row.link+'" type="application/x-shockwave-flash" wmode="transparent" width="320" height="150"></embed></object></div><script type="text/javascript">function onYouTubePlayerReady(playerId) {var ytplayer = document.getElementById("e1");ytplayer.playVideo();}</script></body></html>';
	}else{
		detailViews.wb.url=e.row.link;
	}
	
	detailViews.w.add(detailViews.wb);
	views.nav.open(detailViews.w,{animated:true});
});

function setNews(news){
	var newDate = new Date();
	var dateGroups = [];
	var id = null;
	var item = null;
    for(id in news){
    	if (!isNaN(id)){
    		item=news[id];
			newDate.setTime( item.pubDate*1000 );
			var dateString = newDate.getUTCDate() +' '  + monthNames[newDate.getUTCMonth()];
			dateGroups.push(noticiesViews.getNoticiaRow(id,item.id,item.title,dateString,item.link));
        }
     }
    Ti.API.info('dateGroups.length: ' +dateGroups.length);
	
    views.tableview.setData( dateGroups.reverse(),{ animationStyle : Titanium.UI.iPhone.RowAnimationStyle.DOWN });
}

function loadRSSFeed(xhr){
	if(Ti.Network.networkType == Ti.Network.NETWORK_NONE){
		var alertDialog = Titanium.UI.createAlertDialog({
			title: L('WARNING'),
			message: L('Your device is not online.'),
			buttonNames: ['OK']
        });
		alertDialog.show();
	    return;
	}
	
	var now = getNow();
	var last_news_date = Ti.App.Properties.getInt('last_news_date',now);
	
	if (views.tableview.data==null || (last_news_date == now ||  now > (last_news_date + 300 ))){
		Ti.API.info('ha passat prou temps');
		views.activityIndicatorView.show();
		xhr.open("GET",Ti.App.config.url_rss_gae);
		xhr.setRequestHeader('User-Agent',Ti.App.config.user_agent);
		xhr.onload = function(){
			try{
				views.activityIndicatorView.hide();
				
				var responseText = this.responseText;
				var noticies = JSON.parse(responseText);
				setNews(noticies);
				Ti.App.Properties.setInt('last_news_date',now);
				Ti.App.Properties.setBool("newsLoaded",true);
				Ti.App.Properties.setString("news",responseText);
			}catch(err){}
		};
		xhr.send();
	}else{
		Ti.API.info('no ha passat prou temps:'+last_news_date + ' '+ now + ' loadednews:'+Ti.App.Properties.getBool("newsLoaded"));
		
		if(Ti.App.Properties.getBool("newsLoaded")){
			var noticies_old = JSON.parse(Ti.App.Properties.getString("news"));
			setNews(noticies_old);
		}
	}
}

win.addEventListener('open', function(){ 
	loadRSSFeed(xhr);
});

Ti.App.addEventListener('resume', function(){ 
	loadRSSFeed(xhr);
});

views.refreshButton.addEventListener('click',function(){
	loadRSSFeed(xhr);
});